package com.dc.mqtt.newMqtt;

import com.alibaba.fastjson.JSON;
import com.dc.controller.Controller;
import com.dc.entity.MessageLog;
import com.dc.util.ApplicationContextProvider;
import com.dc.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.dc.mqtt.newMqtt.MqttConfig.INPUT_CHANNEL;

/**
 * mqtt队列监听类
 */
@Slf4j
@Configuration
public class mqttHandler {
    //通过通道获取数据
    @Bean
    @ServiceActivator(inputChannel = INPUT_CHANNEL)
    public MessageHandler handler() {
        return message -> {
            String topic = Objects.requireNonNull(message.getHeaders().get("mqtt_receivedTopic")).toString();
            Controller controller = ApplicationContextProvider.getBean(Controller.class);
            // subscribe后得到的消息会执行到这里面
            log.info("接收消息主题 : {}，接收消息内容 : {}", topic,message.getPayload().toString());
            String content = new String(message.getPayload().toString());
            try {
                MessageLog messageLog = new MessageLog();
                //TODO 根据设备id写入数据库
                Map<String, Object> commonParams = JSON.parseObject(content, Map.class);
                String id = String.valueOf(commonParams.get("id"));
//            if (redisUtil.hasKey(id)) {
//                //如果key存在 就不做任何操作,抛弃当前数据
//            } else {
//                redisUtil.set(id, id, 2L);
                //不存在，就代表是新数据，保存入库
                List<MessageLog> data = controller.queryByBu(id);
//                if (CollectionUtils.isEmpty(data)) {
                messageLog.setBatchId(String.valueOf(commonParams.get("id")));
                messageLog.setDeviceId(String.valueOf(SnowflakeIdWorker.generateId()));
                messageLog.setData(content);
                messageLog.setCountData("0");
                controller.save(messageLog);
//                }
//            }
            } catch (Exception exception) {
                //有可能serviceId为空 有可能serviceId不对拿不到handler
                log.error("处理失败", exception);
            }
        };
    }
}
